package com.ds.lens.data.controller;

import com.ds.lens.data.common.asserts.Asserts;
import com.ds.lens.data.common.constant.Constants;
import com.ds.lens.data.service.LensUserService;
import com.ds.lens.data.vo.BaseOutVO;
import com.ds.lens.data.vo.factory.VOFactory;
import com.ds.lens.data.vo.in.PagedConditionInVO;
import com.ds.lens.data.vo.in.User;
import com.ds.lens.data.vo.in.v2.user.LensUserInVO;
import com.ds.lens.data.vo.in.v2.user.LensUserSearchInVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * Description:
 *
 * @author WeiShaoying
 * @date 2020-02-13
 */

@Slf4j
@RestController
@Api(value = "Lens application controller")
@RequestMapping(produces = {"application/json;charset=UTF-8"})
public class LensUserController {

    @Autowired
    private LensUserService lensUserService;

    /**
     * Query user profile.
     *
     * @return BaseOutVO object
     */
    @ApiOperation(value = "Query user profile.")
    @GetMapping(value = "/lens/user/profile")
    public BaseOutVO userProfile(@RequestAttribute(value = "user") User user) {
        return VOFactory.getSuccessBaseOutVO(lensUserService.userProfile(Long.parseLong(user.getUid()), user.getUserType(), user.isAdmin()));
    }

    /**
     * Query all users from Lens.
     *
     * @return BaseOutVO object
     */
    @ApiOperation(value = "Query all users from Lens.")
    @PostMapping(value = "/lens/user/users")
    public BaseOutVO lensUsers(@RequestBody @Valid PagedConditionInVO<LensUserSearchInVO> inVO,
                               @RequestAttribute(value = "user") User user) {
        return VOFactory.getSuccessBaseOutVO(lensUserService.findLensUsers(inVO));
    }

    /**
     * Query all usernames from Lens.
     *
     * @return BaseOutVO object
     */
    @ApiOperation(value = "Query all usernames from Lens.")
    @GetMapping(value = "/lens/user/usernames")
    public BaseOutVO getAllLensUserNames() {
        return VOFactory.getSuccessBaseOutVO(lensUserService.findAllLensUserNames());
    }

    /**
     * Change password by user.
     *
     * @param inVO inVO
     * @return BaseOutVO object
     */
    @ApiOperation(value = " Change password")
    @PostMapping(value = "/lens/user/change/password")
    public BaseOutVO changePassword(@RequestBody @Valid LensUserInVO inVO,
                                    @RequestAttribute(value = "user") User user) {
        Asserts.assertTrue(user.getUserType() == Constants.UserTypeEnum.LENS.getCode(), Constants.ErrorCode.PARAM_ERROR, "Non-Lens users are not allowed to change passwords.");
        lensUserService.changePassword(Long.parseLong(user.getUid()), inVO.getPassword(), inVO.getNewPassword());
        return VOFactory.getSuccessBaseOutVO();
    }


}
